//
//  LKImagePickerViewController.swift
//  新浪微博
//
//  Created by 胡不归是大虾 on 2016/10/8.
//  Copyright © 2016年 胡不归是大虾. All rights reserved.
//

import UIKit
import SVProgressHUD
private let reuseIdentifier = "Cell"
let imagePickerCellMargin : CGFloat = 4
let colCount :CGFloat =  3
let imagePickerItemW = (ScreenWidth - (colCount + 1) * imagePickerCellMargin ) / colCount
//定义最大可添加的图片数
private let maxImageNum = 5
class LKImagePickerViewController: UICollectionViewController {
    //懒加载图片数组
    lazy var images: [UIImage] = [UIImage]()
    override func viewDidLoad() {
        super.viewDidLoad()
        //注册cell
        self.collectionView!.register(LKImagePickerCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }
    
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //返回图片数组最大加1,如果达到最大数则加1的1不显示,即无法再添加
        return images.count + (images.count == maxImageNum ? 0 : 1)
    }
    
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! LKImagePickerCell
        cell.backgroundColor = UIColor.cyan
        //设置代理对象
        cell.delegate = self
        //因为显示的cell要比数组多一个,所以需要给额外的cell赋值
        if indexPath.item == images.count {
            cell.image = nil
        } else{
            cell.image = images[indexPath.item]
        }
        return cell
    }
    
    
}
//MARK:在分类中遵守cell的协议并且实现代理方法
extension LKImagePickerViewController:LKImagePickerCellDelegate {
    func userWillAddImage() {
        //实例化一个图片选择控制器
        let imagePicker = UIImagePickerController()
        //设置代理
        imagePicker.delegate = self
        //modal控制器
        present(imagePicker, animated: true, completion: nil)
    }
    func userWillRemoveImge(cell: LKImagePickerCell) {
        //获取索引删除数组中指定的元素然后刷新
        let indexPath = collectionView?.indexPath(for: cell)
        images.remove(at: indexPath!.item)
        //如果此时没有图片,隐藏所有cell
        self.view.isHidden = self.images.count == 0
        collectionView?.reloadData()
    }
}
//MARK:实现图片选择控制器的代理方法
extension LKImagePickerViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate
{
    //完成选择后调用的代理方法
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        //得到选中的图片
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        //将图片添加到数组之中
        images.append(image.scaleImage(width: 600))
        //刷新collectionView
        collectionView?.reloadData()
        //推出自身的控制器
        dismiss(animated: true, completion: nil)
    }
}
//MARK:自定义cell的协议
@objc protocol LKImagePickerCellDelegate: NSObjectProtocol {
    //协议方法
    @objc optional func userWillAddImage()
    @objc optional func userWillRemoveImge(cell: LKImagePickerCell)
}
//MARK:自定义cell
class LKImagePickerCell: UICollectionViewCell {
    //声明弱引用的代理成员变量
    weak var delegate: LKImagePickerCellDelegate?
    //声明图片成员变量
    var image : UIImage? {
        didSet {
            addBtn.setImage(image, for: .normal)
            //根据图片是否有值设置删除按钮是否隐藏和添加按钮的背景图片
            removeBtn.isHidden = image == nil
            let bgImage : UIImage? = (image == nil ? #imageLiteral(resourceName: "compose_pic_add") : nil)
            addBtn.setBackgroundImage(bgImage, for: .normal)
        }
    }
    //重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setMyUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //更新ui
    private func setMyUI () {
        //添加控件
        contentView.addSubview(addBtn)
        contentView.addSubview(removeBtn)
        //设置约束
        addBtn.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        removeBtn.snp.makeConstraints { (make) in
            make.top.right.equalToSuperview()
        }
        //为按钮添加响应方法
        addBtn.addTarget(self, action: #selector(addBtnDidClick), for: .touchUpInside)
        removeBtn.addTarget(self, action: #selector(removeBtnDidClick), for:.touchUpInside)
    }
    @objc private func addBtnDidClick () {
        if image != nil {
            SVProgressHUD.showInfo(withStatus: "图片已经存在!")
            return
//            SVProgressHUD.dismiss()
        }
        delegate?.userWillAddImage!()
        //调用添加图片的代理方法
    }
    @objc private func removeBtnDidClick() {
        //调用移除图片的代理方法
        delegate?.userWillRemoveImge!(cell:self)
    }
    //懒加载控件
    //添加图片的按钮
    private lazy var addBtn : UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(#imageLiteral(resourceName: "compose_pic_add"), for: .normal)
        //设置视图显示模式
        btn.imageView?.contentMode = .scaleAspectFill
        return btn
    }()
    //删除图片的按钮
    private lazy var removeBtn : UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(#imageLiteral(resourceName: "compose_photo_close"), for: .normal)
        return btn
    }()
}









